var express = require('express');
var router = express.Router();
const {Course,User,Category,Chapter} = require('../models');
const { where } = require('sequelize');
const { failure, success, NotFoundError } = require('../utils/response');

// 前台接口，此接口为课程详情
router.get('/:id', async function(req, res, next) {
  try {
    const {id} = req.params

    const condition = {
      attributes:{exclude:['categoryId','userId']},
      include:[
        {
            model:Category,
            as:'category',
            attributes:['id','name']
        },
        {
            model:Chapter,
            as:'chapters',
            attributes:['id','title','rank','createdAt'],
            order:[['rank','ASC'],['id','DESC']]
        },
        {
            model:User,
            as:'user',
            attributes:['id','username','nickname','avatar','company']
        },
      ]
    }

    const course = await Course.findByPk(id,condition)
    if(!course){
        throw new NotFoundError(`ID为${id}的课程未找到`)
    }
    success(res,'查询课程详情成功',{course})
  } catch (error) {
    failure(res,error)
  }
});

module.exports = router;
